package com.lobstar.xrpc.service.base;

import java.util.Map;

import com.lobstar.xrpc.common.po.SMessage;
import com.lobstar.xrpc.service.base.ServiceScanner.Invoker;

public class ServiceInvoker {

	private ServiceScanner serviceScanner;
	private static ClassFactory classFactory;
	private String basePackage;

	public ServiceInvoker(String basePackage) {
		serviceScanner = ServiceScanner.initScanner();
		serviceScanner.addClassNewer(ServiceInvoker.classFactory);
		this.setBasePackage(basePackage);
		serviceScanner.loadClasses(basePackage);
	}

	public Object invoke(SMessage message) throws Exception {
		String method = message.getMethod();
		Map<String, Object> params = message.getParams();
		Invoker methodInvoker = serviceScanner.getInvokeMap().get(method);
		return methodInvoker.invoke(params);
	}
	public boolean hasMethod(SMessage message) {
		return serviceScanner.getInvokeMap().containsKey(message.getMethod());
	}

	public static ServiceInvoker buildInvoker(String basePackage) {
		if(basePackage == null) {
			return null;
		}
		return new ServiceInvoker(basePackage);
	}
	public static void setFactory(ClassFactory newer) {
		ServiceInvoker.classFactory = newer;
	}

	public String getBasePackage() {
		return basePackage;
	}

	public void setBasePackage(String basePackage) {
		this.basePackage = basePackage;
	}
}
